<?php

class User extends CActiveRecord
{
    
    
        const NOT_MEMBER = 2;
        const MEMBER     = 1;           
        const MENBER_PAGE = 20;
	/**
	 * The followings are the available columns in table 'tbl_user':
	 * @var integer $id
	 * @var string $username
	 * @var string $password
	 * @var string $salt
	 * @var string $email
	 * @var string $profile
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'cad_user';
	}

	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username, password,nome,email', 'required'),
			array('username,nome, password,classe,img_detail,party, classe, email, salt', 'length', 'max'=>128),
			array('profile', 'safe'),
                        array('img', 'file','on'=>'insert', 'types'=>'jpg, gif, png','allowEmpty'=>false),//exige foto
                        array('img', 'file','on'=>'update', 'types'=>'jpg, gif, png','allowEmpty'=>true), //altera sem foto
			//campos que vao nos formularios como busca
			array('id, username,classe, email, party, profile', 'safe', 'on'=>'search'),
		);
	}

        /**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
                        'FK_img' => array(self::BELONGS_TO, 'cad_galeria', 'author_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'Código',
			'username' => 'Login',
                        'nome'=>'Nome', 
			'password' => 'Senha',
			'salt' => 'Salt',
			'email' => 'Email',
			'profile' => 'Descrição',
                        'classe'=> 'Parceiro',
                        'party'=>'Grupo',
                        'img'=>'Foto',
                        'img_detail'=>'Titulo da foto',
		);
	}
        
	public function findRules($tabela,$pagina)
	{
            $return = false;
           if(!empty(Yii::app()->user->id)){ 
            $models = User::model()->findAll(array('condition'=>'id=:x', 'params'=>array(':x'=>Yii::app()->user->id)));
                foreach($models as $model)            
                  $grupo = $model->party;
            $permi = cad_grupos::model()->loadTableGrupos($grupo);
            
            if($permi == 'admin'){
                $return = true;
            }else{                      
              $rules = $this->perfis($tabela);
              $_rules = array_search($pagina, $rules); 
 
             if($rules[$_rules] == 'default' || $rules[$_rules] == ''){
                $return = false;                
             }else
                $return = true;                 
         
             if(Yii::app()->user->isGuest){
                $return = false;
             }            
           }
         }
            
                return $return;
        }
        
        public function perfis($tabela){
            $ar = array();
            $lista  = array();
            $permission = '';
            $user   = $this->findAll(array('order'=>'id', 'condition'=>'id=:x', 'params'=>array(':x'=>Yii::app()->user->id)));
           foreach($user as $users) 
                $party = $users['party'];
            if(!empty($party)){
                //$rules = cad_roles::model()->findAll(array('condition'=>'perfil=:x and "table" like :v', 'params'=>array(':x'=>$party,':v'=>$tabela)));           
                $sql = 'select * from cad_roles a where perfil = '.$party.' and a.table like "'.$tabela.'"';
                $rules = Yii::app()->db->createCommand($sql)->queryAll();    
               foreach($rules as $permission){
                   $permission = $permission['permission'];
               } 
            }
           if($permission == '')                
            return array('default');   
           else{
            $retorno = explode(',',$permission);    
            return  $retorno;  
           } 
        }
        
       
	public function perfisParty()
	{         
            $ar = array();
            $user =$this->findAll(array('order'=>'id', 'condition'=>'id=:x', 'params'=>array(':x'=>Yii::app()->user->id)));
           foreach($user as $users){  

             return array(cad_grupos::loadTableGrupos($users['party']));   
           }
	}
        
        
	public function loadUsers()
	{

                $criteria=new CDbCriteria;
                $criteria->compare('id',$this->id,true);
                $criteria->condition='Party = '.User::MEMBER;

                $dataProvider = new CActiveDataProvider('User', array(
                 'criteria'=>$criteria,
                     'pagination'=>array(
                           'pageSize'=>User::MENBER_PAGE,
                     ),
               ));
              

	  return $dataProvider;
	}

	public function loadUsersMenu()
	{         
            $ar = array();

            $user =$this->findAll(array('order'=>'id', 'condition'=>'party=:x', 'params'=>array(':x'=>User::MEMBER)));
           foreach($user as $users){
               $ar[] = array('label'=>$users['username'], 'url'=>array('user/profile&id='.$users['id']), 'linkOptions' => array( 'class' => 'menulink' ));
           }
	  return $ar;
	}

        
	public static function loadTableUser($id=null)
	{
	    if(!isset($id)){
                $lista  = array();
                $models = User::model()->findAll();
                foreach($models as $model){
			//$lista[$model->cad_associacao]['id']   = $model->$model->cad_associacao;
                        $lista[$model->id] = $model->nome;
                }
               return $lista;
            }else{
                   $models = User::model()->findAll(array('condition'=>'id=:x', 'params'=>array(':x'=>$id)));
                foreach($models as $model)
                  return $model->nome;
            }
	}         
        
        
	public function authenticateUsername($username)
	{
		$user=User::model()->find('LOWER(username)=?',array(strtolower($username)));
		return  ($user===null) ?  false :true;
			
	} 
        
        
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);

		$criteria->compare('username',$this->username,true);

		$criteria->compare('password',$this->password,true);

		$criteria->compare('email',$this->email,true);

                $criteria->compare('classe',$this->classe,true);

		$criteria->compare('profile',$this->profile,true);
                
                $criteria->compare('img',$this->img,true);
                
		$criteria->compare('party',$this->party,true);
                
		return new CActiveDataProvider('user', array(
			'criteria'=>$criteria,
		));
	}        

	/**
	 * Checks if the given password is correct.
	 * @param string the password to be validated
	 * @return boolean whether the password is valid
	 */
	public function validatePassword($password)
	{
		return $this->hashPassword($password,$this->salt)===$this->password;
	}

	/**
	 * Generates the password hash.
	 * @param string password
	 * @param string salt
	 * @return string hash
	 */
	public function hashPassword($password,$salt)
	{
		return md5($salt.$password);
	}

	/**
	 * Generates a salt that can be used to generate a password hash.
	 * @return string the salt
	 */
	public function generateSalt()
	{
		return uniqid('',true);
	}
              
}